package org.ourguy.mymoviesandshows;

import java.util.ArrayList;

import org.ourguy.mymoviesandshows.adapters.ShowsAdapter;
import org.ourguy.mymoviesandshows.datamodel.ITitle;
import org.ourguy.mymoviesandshows.managers.DataAccessException;
import org.ourguy.mymoviesandshows.managers.DataAccessManager;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.GestureDetector;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class TrendingShowsActivity extends ListActivity {
	
	/**
	 * The adapter for this activity
	 */
	private DataAccessManager menager;
	private ShowsAdapter adapter;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        menager = DataAccessManager.getInstance(this);
        // Registering the list view for a context menu
        registerForContextMenu(getListView());
		
        // Registering an on-click listener for the list
		getListView().setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				startTitleInfoActivity(position);
			}
		});
		
		// Get the trends
		new DownloadTrendingList(TrendingShowsActivity.this).execute();
		
		// sliding between tabs
		final TabActivity parrent = (TabActivity) getParent();
		final GestureDetector mGestureDetector = new GestureDetector(this,
				new GestureDetector.SimpleOnGestureListener() {

					public boolean onFling(MotionEvent e1, MotionEvent e2,
							float velocityX, float velocityY) {
						int dx = (int) (e2.getX() - e1.getX());
						// don't accept the fling if it's too short
						// as it may conflict with a button push
						if (Math.abs(dx) > 300 && Math.abs(velocityX) > 200) {
							if (velocityX > 0) {
								parrent.getTabHost().setCurrentTab(0);
							} else {
								parrent.getTabHost().setCurrentTab(2);
							}
							return true;
						} else {
							return false;
						}
					}
				});

		View.OnTouchListener gestureListener = new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				return mGestureDetector.onTouchEvent(event);
			}
		};

		getListView().setOnTouchListener(gestureListener);
    }
    
    private void startTitleInfoActivity(int position) {
    	Intent intent = new Intent(getApplicationContext(), ShowActivity.class);
		ITitle show = (ITitle)getListAdapter().getItem(position);
    	intent.putExtra("show", show.getApiId());
		this.startActivity(intent);
    }
    @Override
    public void onStop() {
    	super.onStop();
    	try {
    		menager.saveState(TrendingShowsActivity.this);
    		Toast.makeText(TrendingShowsActivity.this, "saved state", Toast.LENGTH_LONG);
    	} catch (Exception ignored) {}
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	
        AdapterContextMenuInfo info =
        		(AdapterContextMenuInfo) item.getMenuInfo();
        
        switch (item.getItemId()) {
            case R.id.menuTitleInfo:
            	startTitleInfoActivity(info.position);
                return true;
            case R.id.menuRemoveFromTracking:
            	ITitle selected = (ITitle) getListAdapter().getItem(info.position);
            	if(selected.isInFavorites())
            		menager.removeFromFavorites(selected, TrendingShowsActivity.this);
            	else
            		menager.addToFavorites(selected, TrendingShowsActivity.this);
            	adapter.notifyDataSetChanged();
            	return true;
            default:
                return super.onContextItemSelected(item);
        }
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
        
        ITitle selected = (ITitle) getListAdapter().getItem(info.position);
        
        menu.setHeaderTitle(selected.getTitle());
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context_menu_tracking_list, menu);
        
        if (selected.isInFavorites()) {
        	menu.findItem(R.id.menuRemoveFromTracking)
        			.setTitle("Remove from tracking list");
        } else {
        	menu.findItem(R.id.menuRemoveFromTracking)
        			.setTitle("Add to tracking list");
        }
        
    }
    
    private class DownloadTrendingList extends AsyncTask<Void, Void, Boolean> {
    	private ListActivity activity;
    	private ProgressDialog dialog;
    	private Context context;
    	private ArrayList<ITitle> titleList = null;
    	
    	public DownloadTrendingList(ListActivity activity) {
    		this.activity = activity;
    		this.context = activity;
    		dialog = new ProgressDialog(context);
    	}
    	
    	@Override
    	protected void onPreExecute() {
    		this.dialog.setMessage("Please wait until the list is downloaded");
    		this.dialog.setIndeterminate(true);
    		this.dialog.show();
    	}

		@Override
		protected Boolean doInBackground(Void... arg0) {
	        try {
	        	titleList = menager.getTrending();
	        } catch (DataAccessException e) {
	        	return false;
	        }
	        return true;
		}
		
		@Override
		protected void onPostExecute(final Boolean success) {
			if (dialog.isShowing())
				dialog.hide();
			
			if(success) {
				adapter = new ShowsAdapter(context, titleList);
				activity.setListAdapter(adapter);
				adapter.notifyDataSetChanged();
			} else {
				Toast.makeText(context, "Error loading titles list",
						Toast.LENGTH_LONG);
			}
		}
    }
}
